import logging
import random
import string

from django.shortcuts import render
from django.http import JsonResponse
from rest_framework.parsers import JSONParser
from rest_framework.decorators import api_view
from .models import customer, company


# Create your views here.

# 判空的公共方法
def is_empty(n):
    return n is None or str(n).strip() == ''


# 客户注册
@api_view(['POST'])
def register(request):
    data = JSONParser().parse(request)
    name = data.get('name')
    email = data.get('email')
    phone = data.get('phone')
    company_id = data.get('company_id')
    if is_empty(name) or is_empty(email) or is_empty(phone) or is_empty(company_id):
        return JsonResponse({
            'error': '参数项不能为空'
        }, status=400)
    # 判重
    if customer.objects.filter(email=email).exists():
        return JsonResponse({
            'error': '账号已存在'
        }, status=404)
    customer(name=name, email=email, phone=phone, company_id_id=company_id).save()
    return JsonResponse({
        'code': 200,
        'msg': '注册成功',
        'data': data
    })


# 模糊查询name
@api_view(['GET'])
def mohu(request):
    name = request.GET.get('name')
    if is_empty(name):
        obj = customer.objects.filter()
        lis = []
        for item in obj:
            lis.append({
                'name': item.name,
                'email': item.email,
                'phone': item.phone,
                '公司名称': item.company_id.company_name
            })
        return JsonResponse({
            'code': 200,
            'data': lis
        })
    objs = customer.objects.filter(name=name)
    lis = []
    for item in objs:
        lis.append({
            'name': item.name,
            'email': item.email,
            'phone': item.phone,
            '公司名称': item.company_id.company_name
        })
    return JsonResponse({
        'code': 200,
        'data': lis
    })


# 修改
@api_view(['PUT'])
def updata(request):
    data = JSONParser().parse(request)
    name = data.get('name')
    customer_id = data.get('customer_id')
    email = data.get('email')
    phone = data.get('phone')
    company_id = data.get('company_id')
    if customer.objects.filter(id=customer_id).exists() is False:
        return JsonResponse({
            'error': '用户不存在'
        }, status=400)
    obj = customer.objects.get(id=customer_id)
    obj.name = name
    obj.email = email
    obj.phone = phone
    obj.company_id_id = company_id
    obj.save()
    return JsonResponse({
        'msg': '修改成功',
        'data': data
    })


# 多表查询
@api_view(['GET'])
def getindustryinfo(request):
    flag,name=checktoken(request)
    if flag is False:
        return JsonResponse({
            'error':'未登录，不可查询信息'
        },status=404)

    industry = request.GET.get('industry')
    if is_empty(industry):
        companyobjs = company.objects.filter()
        lis = []
        for companyobj in companyobjs:  # 每个公司数据对象      #公司下每个客户对象
            for customerobj in companyobj.customer.all():  # 公司下所有客户的对象
                lis.append({
                    'customername': customerobj.name,
                    'customeremail': customerobj.email,
                    'customerphone': customerobj.phone,
                    '公司名称': companyobj.company_name,
                    '公司地址': companyobj.address,
                    '公司行业': companyobj.industry
                })
        return JsonResponse({
            'code': 200,
            'data': lis
        })

    companyobjs = company.objects.filter(industry=industry)
    lis = []
    for companyobj in companyobjs:
        for customerobj in companyobj.customer.all():  # 公司下所有客户的对象
            lis.append({
                'customername': customerobj.name,
                'customeremail': customerobj.email,
                'customerphone': customerobj.phone,
                '公司名称': companyobj.company_name,
                '公司地址': companyobj.address,
                '公司行业': companyobj.industry
            })
    return JsonResponse({
        'code': 200,
        'data': lis
    })



from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
# 分页
@api_view(['GET'])
def pagedata(request):
    flag, name = checktoken(request)
    if flag is False:
        return JsonResponse({
            'error': '未登录，不可查询信息'
        }, status=404)

    # 请求第几页数据
    page = request.GET.get('page')
    # 一页显示几条数据
    pagesize = request.GET.get('pagesize')
    # 获取表中所有数据
    alldata = customer.objects.filter().values()
    logging.info(f'查看的所有数据格式：{alldata}')
    # 分页设置
    pageobjall = Paginator(alldata, pagesize)
    try:
        singlepageobj = pageobjall.page(page)
    # 页码不存在
    except EmptyPage:
        singlepageobj = pageobjall.page(pageobjall.num_pages)
    # 页码不是一个整型数字
    except PageNotAnInteger:
        singlepageobj = pageobjall.page(1)
    # 定义一个空列表用于存数用
    lis = []
    for item in singlepageobj.object_list:
        lis.append({
            "名称": item.get('name'),
            "邮箱": item.get('email'),
            "手机号": item.get('phone'),
        })
    return JsonResponse({
        'code': 200,
        'msg': '请求成功',
        'data': lis,
        'page': {
            'page': page,
            'pagesize': pagesize,
            'total': alldata.count()
        }
    })

from django.core.signing import Signer
from django.core.cache import cache
from datetime import timedelta
#鉴权
#创建token
def createtoken(name):
    randomstr=''.join(random.choices(string.ascii_letters,k=8))
    token=Signer().sign(randomstr+name)
    cache.set(f'test_{name}',token,timeout=timedelta(minutes=100).total_seconds())
    return token

#校验token
def checktoken(request):
    reqtoken=request.META.get('HTTP_TOKEN')
    if reqtoken is None:
        return False,'xxxx'
    untoken=Signer().unsign(reqtoken)
    name=untoken[8:]
    cachetoken=cache.get(f'test_{name}')
    if cachetoken is None:
        return False,'xxxx'
    return True,name

#登录
@api_view(['POST'])
def login(request):
    data=JSONParser().parse(request)
    email=data.get('email')
    phone=data.get('phone')
    obj=customer.objects.get(email=email)
    if obj.phone==phone:
        token=createtoken(email)
        return JsonResponse({
            'code':200,
            'msg':'登录成功',
            'token':token
        })


